package model

import "gorm.io/gorm"

// UserTenantRelModelClient 用户模型客户端
type UserTenantRelClient struct {
	db *gorm.DB
}

func NewUserTenantRelClient(db *gorm.DB) *UserTenantRelClient {
	return &UserTenantRelClient{db: db}
}

// 创建用户租户关系
func (c *UserTenantRelClient) Create(userTenantRel *UserTenantRel) error {
	return c.db.Create(userTenantRel).Error
}

// 查询用户租户关系
func (c *UserTenantRelClient) FindByUserID(userID string) ([]*UserTenantRel, error) {
	var userTenantRels []*UserTenantRel
	err := c.db.Where("user_id = ?", userID).Find(&userTenantRels).Error
	return userTenantRels, err
}

// 批量查询用户租户关系
func (c *UserTenantRelClient) BatchFindByUsers(users []string) (map[string][]*UserTenantRel, error) {
	var userTenantRels []*UserTenantRel
	err := c.db.Where("user_id in ?", users).Find(&userTenantRels).Error
	if err != nil {
		return nil, err
	}

	// 预分配map容量以提高性能
	result := make(map[string][]*UserTenantRel, len(users))

	// 先为所有查询的用户初始化空切片
	for _, user := range users {
		result[user] = make([]*UserTenantRel, 0)
	}

	// 填充数据
	for _, rel := range userTenantRels {
		userID := rel.UserID
		result[userID] = append(result[userID], rel)
	}

	return result, nil
}

// 查询租户绑定的用户ID列表
func (c *UserTenantRelClient) BatchFindByTenantIDs(tenants []string) ([]*UserTenantRel, error) {
	var userTenantRels []*UserTenantRel
	if err := c.db.Model(&UserTenantRel{}).Where("tenant_id in (?)", tenants).Find(&userTenantRels).Error; err != nil {
		return nil, err
	}
	return userTenantRels, nil
}
